<template>
  <div class="app-container">
    <el-form :inline="true" :model="getFormDate" class="demo-form-inline">
      <el-form-item>
        <el-input size="mini" v-model="getFormDate.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getUsers" size="mini">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-button style="margin-bottom: 5px;" size="mini" @click="add">新增</el-button>
    <el-button style="margin-bottom: 5px;" size="mini" @click="handlerBatchDelete">批量删除</el-button> -->
    <el-table size="mini" :data="tableData" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" @click="setPermission(scope.$index, scope.row)">权限设置</el-button> -->
          <!-- <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
          <el-button v-if="scope.row.status == 1" size="mini" type="text" @click="handleCheck(scope.$index, scope.row)">审核</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="申请人">
      </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="status" label="进度">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1" type="warning">申请中</el-tag>
          <el-tag v-if="scope.row.status == 2" type="success">审核通过</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="float: right;margin-top: 5px;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize"
      layout="prev, pager, next, jumper" :total="totalNum">
    </el-pagination>
    <el-dialog title="添加" :visible.sync="dialogVisibleAdd" width="30%">
      <el-form :model="addFormData" label-width="80px" ref="addFormData">
        <el-form-item label="名称">
          <el-input v-model="addFormData.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="优惠力度">
          <el-input v-model="addFormData.price" placeholder="请输入优惠力度"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="createApply">确认</el-button>
          <el-button @click="resetFormAdd('addFormData')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="修改" :visible.sync="dialogVisibleUpdate" width="30%">
      <el-form :model="updateFormData" label-width="80px">
        <el-form-item label="申请人">
          <el-input v-model="updateFormData.name" placeholder="请输入申请人"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="updateFormData.mobile" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="进度">
          <el-switch v-model="updateFormData.status" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button @click="updateApply">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="权限设置" :visible.sync="dialogVisibleSetPermisssion" width="30%">
      <el-tree ref="treeData" :data="treeData" show-checkbox node-key="id" :default-expanded-keys="defaultExpandedKeys"
        :default-checked-keys="defaultCheckedKeys" :props="defaultProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleSetPermisssion = false">取 消</el-button>
        <el-button size="mini" @click="getAllCheckedKeys">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getApplyByPage, deleteApply, getApplyById, updateApplyById,
  batchDeleteApply, addApply
} from "@/api/apply.js"
export default {
  data() {
    return {
      list: null,
      listLoading: true,
      getFormDate: {},
      roles: [],
      tableData: [],
      multipleSelection: [],
      ids: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogVisibleAdd: false,
      dialogVisibleUpdate: false,
      dialogVisibleSetPermisssion: false,
      updateFormData: {},
      addFormData: {
        username: '',
        password: '',
        nickName: '',
        gender: '',
        mobile: '',
        email: '',
        roles: '',
      },
      defaultExpandedKeys: [],
      defaultCheckedKeys: [],
      pageSize: 10,
      currentPage: 1,
      totalNum: 0,
      updateId: ''
    }
  },
  created() {
    this.initTableData()
    this.initTreeDate()
  },
  methods: {
    handleCheck(index, row){
      getApplyById(row.id).then(res => {
        let senddata = {
          ...res.data.data,
          status: 2
        }
        updateApplyById(senddata).then(res => {
          if(res.data.code == 200){
            this.$message.success("审核通过")
            this.initTableData()
          }
        })
      })
    },
    setPermission(index, row) {
      this.defaultCheckedKeys = []
      // if (row.permissionList) {
      //   this.defaultExpandedKeys = row.permissionList.map(item => {
      //     return item.id
      //   })
      //   this.defaultCheckedKeys = this.defaultExpandedKeys
      // }
      getPermissionByApplyId(row.id).then(res => {
        if (res.data.code == 200) {
          if (res.data.data.length > 0) {
            this.defaultExpandedKeys = res.data.data.map(item => {
              return item.id
            })
            this.defaultCheckedKeys = this.defaultExpandedKeys
          }
        }
      })
      this.dialogVisibleSetPermisssion = true
      this.updateId = row.id
    },
    initTreeDate() {
      getPermissionTreeList().then(res => {
        if (res.data.code == 200) {
          this.treeData = res.data.data
        }
      })
    },
    resetFormAdd(formName) {
      this.addFormData = {}
      this.$refs[formName].resetFields();
    },
    createApply() {
      addApply(this.addFormData).then(res => {
        if (res.data.code == 200) {
          this.$message.success("添加成功")
          this.dialogVisibleAdd = false
          this.initTableData();
        }
      })
    },
    getAllCheckedKeys() {
      const treeDataRef = this.$refs.treeData;
      // getCheckedNodes:全选的集合，getHalfCheckedNodes半选的集合
      // , ...treeDataRef.getHalfCheckedNodes()
      const treeDataList = [...treeDataRef.getCheckedNodes(), ...treeDataRef.getHalfCheckedNodes()];
      let tableDataIds = treeDataList.map(item => {
        return item.id
      })
      setPermissions(this.updateId, tableDataIds).then(res => {
        if (res.data.code == 200) {
          this.$message.success("权限设置成功")
          this.dialogVisibleSetPermisssion = false
        }
      })
    },
    updateApply() {
      updateApplyById(this.updateFormData).then(res => {
        if (res.data.code == 200) {
          this.$message.success("修改成功")
          this.dialogVisibleUpdate = false
          this.initTableData();
        }
      })
    },
    handlerBatchDelete() {
      if (this.multipleSelection.length > 0) {
        this.ids = this.multipleSelection.map(item => {
          return item.id
        })
        batchDeleteApply(this.ids).then(res => {
          if (res.data.code == 200) {
            this.$message.success("批量删除成功")
            this.initTableData()
          }
        })
      } else {
        this.$message.warning("请先选择删除项")
      }
    },
    initTableData(page) {
      let senddata = {
        ...this.getFormDate,
        size: this.pageSize,
        page: page ? page : this.currentPage
      }
      getApplyByPage(senddata).then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data.records
          this.totalNum = res.data.data.total
          this.defaultExpandedKeys = res.data.data.records.map(item => {
            return item.id
          })
        }
      })
    },
    add() {
      this.dialogVisibleAdd = true
    },
    handleEdit(index, row) {
      this.dialogVisibleUpdate = true
      getApplyById(row.id).then(res => {
        if (res.data.code == 200) {
          this.updateFormData = res.data.data
        }
      })
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteApply(row.id).then(res => {
          if (res.data.code == 200) {
            this.$message.success("删除成功")
            this.initTableData();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getUsers() {
      this.initTableData();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.initTableData(val)
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? cityOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    }
  }
}
</script>

<style>
.el-dialog {
  position: absolute;
  top: -40px;
  margin-left: 550px;
}
</style>